<template>
    <u-sticky bgColor="#F5F6F8">
        <view class="tabs">
            <u-tabs itemStyle="height: 100rpx;width: 33%;font-size: 30rpx;'" lineColor="#5780EF"
                    activeStyle="color: #5780EF;" inactiveStyle="color: #606672;" :current="current" :list="tabsList"
                    @click="tabsChange"></u-tabs>
        </view>
    </u-sticky>

    <u-popup closeable bgColor="transparent" :show="paymentPop" @close="paymentPop = false">
        <view class="cancel-pop">
            <view class="pop-title">支付订单</view>
            <view class="info">
                <view>预约项目: {{paymentOrder.project_name}}</view>
                <view> {{paymentOrder.doctor_name}} {{paymentOrder.treatment_date}} {{paymentOrder.treatment_time}}-{{paymentOrder.treatment_end_time}}</view>
                <view style="margin-bottom: 0;">就诊人：{{paymentOrder.project_name}} {{paymentOrder.patient_mobile}}</view>
            </view>
            <view class="pop-title">请选择支付方式：</view>
            <view class="radio-wrap">
                <u-radio-group v-model="paymentWay" placement="column" @change="handlePaymentWayChange">
                    <view class="payment-item" @click="handleSelectPayment('wechat')">
                        <view class="left">
                            <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a40.png')"></u-image>
                            <view class="pay-name">微信支付</view>
                        </view>
                        <view class="right">
                            <u-radio activeColor="#516DDB" name="wechat"></u-radio>
                        </view>
                    </view>
                    <view class="payment-item center" @click="handleSelectPayment('balance')">
                        <view class="left">
                            <u-image width="40rpx" height="40rpx" src="/static/images/a41.png"></u-image>
                            <view class="pay-name">余额支付</view>
                            <view class="pay-tip">当前余额：{{userStore.store_balance}}元</view>
                        </view>
                        <view class="right">
                            <u-radio activeColor="#516DDB" name="balance"></u-radio>
                        </view>
                    </view>
                    <view class="payment-item" @click="handleSelectPayment('coupon')">
                        <view class="left">
                            <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a42.png')"></u-image>
                            <view class="pay-name">抵扣券支付</view>
                        </view>
                        <view class="right">
                            <u-radio activeColor="#516DDB" name="coupon"></u-radio>
                        </view>
                    </view>
                </u-radio-group>
            </view>
            <view class="btn">
                <u-button throttleTime="1000"
                          :customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}"
                          :hairline="false" type="mini" shape="circle"
                          color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                          @tap="toPay(paymentOrder.id)"
                >确认</u-button>
            </view>
        </view>
    </u-popup>

    <view class="order-list">
        <view class="order-item" v-for="(item, i) in orderList" :key="i" @tap="goOrderDetail(item)">
            <view class="status-box">
                <view class="name">{{ item.patient_name }}</view>
                <view class="status" style="display: flex;" v-if="item.status == 1">
                    待支付
                    <uni-countdown :font-size="14" color="#DD815F" :show-day="false"
                                   :hour="item.remainingTime.hours"
                                   :minute="item.remainingTime.minutes"
                                   :second="item.remainingTime.seconds" />
                </view>
                <view class="status" v-if="item.status == 2">待就诊</view>
                <view class="status1" v-if="item.status == 3">已完成</view>
                <view class="status1" v-if="item.status == 0">已取消</view>
            </view>
            <view class="content-box">
                <view class="icon">
                    <u-image width="180rpx" height="180rpx" :src="getServerStatic('/static/images/a21.png')"></u-image>
                </view>
                <view class="icon">
                    <u-image width="180rpx" height="180rpx" :src="getServerStatic('/static/images/a21.png')"></u-image>
                </view>
                <view class="content-item">医院：{{ item.hospital_name }}</view>
                <view class="content-item">预约项目：{{ item.project_name }}</view>
                <view class="content-item">医生：{{ item.doctor_name }}</view>
                <view class="content-item" style="margin-bottom: 0;">就诊日期：{{ item.treatment_date }} {{item.treatment_time}}-{{item.treatment_end_time}}</view>
<!--                <view class="content-item">已超时：请退号后重新预约</view>-->
            </view>
            <view class="btns-box">
                <view class="message" v-if="item.status == 2 ||item.status == 1 ">请在就诊当天前往医院就诊</view>
                <view class="">
                    <u-button
                      throttleTime="1000"
                      :customStyle="{height: '56rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}"
                      :hairline="false" type="mini" shape="circle"
                      color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                      @tap.stop="actionPay(item)"
                      v-if="item.status == 1"
                    >
                        去支付
                    </u-button>
                    <!-- <u-button throttleTime="1000" :customStyle="{height: '56rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)">退号</u-button> -->
                </view>
            </view>
        </view>

        <u-loadmore :status="loadMoreStatus" />
    </view>

</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow, onPullDownRefresh , onReachBottom} from '@dcloudio/uni-app'
    import {getOrderList, initiatePayment} from "@/api/order"
    import useUniAPi from "@/hooks/useUniAPi";
    import {useUserStore} from "@/store";
    import {getServerStatic} from "@/utils/tool";
    const { navigateTo, redirectTo, goBack, payment } = useUniAPi()

    // 用户store
    const userStore = useUserStore();

    const current = ref(0)
    const tabsList = ref([
        {
            name: '全部',
            type: 'all',
        },
        {
            name: '待支付',
            type: 'pending',
        },
        {
            name: '待就诊',
            type: 'paid',
        },
    ])
    const status = ref('all')
    const orderList = ref([])
    // loadmore loading nomore
    const loadMoreStatus = ref('loadmore')
    const currentPage = ref(1)
    const perPage = ref(10)
    const tabsChange = (e) => {
        current.value = e.index
        status.value = e.type
        refreshPage()
        handleGetOrderList()
    }
    const goOrderDetail = (item) => {
        uni.navigateTo({
            url: `/mine/order/detail?orderId=${item.id}`
        })
    }

    onLoad((evt) => {
        console.log('订单列表', evt)
        // 同步用户信息
        userStore.syncUserInfo()
    })

    onShow(() => {
        refreshPage()
        handleGetOrderList()
    })

    onReachBottom(() => {
        handleGetOrderList()
        console.log("上拉加载更多")
    })

    // 刷新数据.
    const refreshPage = () => {
        currentPage.value = 1
        orderList.value = []
    }

    // 获取参数.
    const getSearchParams = () => {
        return {
            status: status.value,
            currentPage: currentPage.value,
            perPage: perPage.value,
        }
    }

    // 列表数据
    const handleGetOrderList = async () => {
        let param = getSearchParams()
        loadMoreStatus.value = 'loading'

        const {code, data, message} = await getOrderList(param)
        if (code === 1) {
            if (data.length <= 0) {
                loadMoreStatus.value = 'nomore'
                console.log('noting')
            } else {
                currentPage.value++
                // 数量少于每页数量
                if (data.length < perPage.value) {
                    loadMoreStatus.value = 'nomore'
                } else {
                    loadMoreStatus.value = 'loadmore'
                }
            }

            let list = data.map(item => {
                // 克隆对象
                const clonedItem = { ...item };

                // 计算剩余时间
                const endTime = new Date(item.payment_end_time).getTime();
                const currentTime = new Date().getTime();
                const timeDifference = Math.max(0, endTime - currentTime); // 确保剩余时间不为负数

                const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
                const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
                const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

                // 将计算得到的时分秒添加到克隆的对象中
                clonedItem.remainingTime = {
                    // hours: hours < 10 ? '0' + hours : hours,
                    // minutes: minutes < 10 ? '0' + minutes : minutes,
                    // seconds: seconds < 10 ? '0' + seconds : seconds
                    hours: hours < 10 ?  hours : hours,
                    minutes: minutes < 10 ? minutes : minutes,
                    seconds: seconds < 10 ? seconds : seconds
                };

                return clonedItem;
            })

            orderList.value = orderList.value.concat(list)
        } else {
            loadMoreStatus.value = 'nomore'
        }
    }


    // 支付方式
    const paymentWay = ref('wechat')
    const handlePaymentWayChange = (e) => {
        paymentWay.value = '' + e;
    }

    const handleSelectPayment = (way) => {
        paymentWay.value = way;
    }

    const paymentPop = ref(false)
    // 待支付订单信息
    const paymentOrder = reactive({
        id: '',
        project_name: "",
        doctor_name: "",
        treatment_date: "",
        treatment_time: "",
        treatment_end_time: "",
        price: "0.00",
        order_no: '',
        patient_name: "",
        patient_age: "",
        patient_mobile: "",
    })

    const actionPay = (order) => {
        paymentOrder.id = order.id
        paymentOrder.project_name = order.project_name
        paymentOrder.doctor_name = order.doctor_name
        paymentOrder.treatment_date = order.treatment_date
        paymentOrder.treatment_time = order.treatment_time
        paymentOrder.treatment_end_time = order.treatment_end_time
        paymentOrder.price = order.price
        paymentOrder.order_no = order.order_no
        paymentOrder.patient_name = order.patient_name
        paymentOrder.patient_age = order.patient_age
        paymentOrder.patient_mobile = order.patient_mobile
        paymentPop.value = true
    }

    // 发起支付.
    const toPay = async (orderId) => {
        paymentPop.value = false
        console.log('订单ID', orderId)

        uni.showLoading({
            title: '加载中'
        });
        const { code, data, message } = await initiatePayment({orderId: orderId, method: paymentWay.value})

        console.log('发起支付', data)
        uni.hideLoading();
        if (code == 1) {
            if (paymentWay.value == 'wechat') {
                const result =  await payment(data)
                console.log('发起支付结果',result)
                // {errMsg: "requestPayment:ok"}
                if (result?.errMsg && result.errMsg == 'requestPayment:ok') {
                    console.log('支付完成')
                    uni.showToast({
                        mask: true,
                        title: '支付完成',
                        icon: 'success'
                    })
                    refreshPage()
                    await handleGetOrderList()
                }
            } else {
                uni.showToast({
                    mask: true,
                    title: '支付完成',
                    icon: 'success'
                })
                refreshPage()
                await handleGetOrderList()
            }

        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
            return false
        }
    }
</script>

<style lang="scss" scoped>
.order-list {
    margin-top: 40rpx;
    padding: 0 26rpx 150rpx;
    .order-item {
        padding: 38rpx;
        background: #FFFFFF;
        border-radius: 30rpx;
        margin-bottom: 26rpx;
        box-shadow: 0 0 20rpx 1rpx rgba(187,187,187,.16);

        .status-box {
            @include between(100%);
            padding-bottom: 32rpx;
            border-bottom : 1rpx solid #E8E8E8;
            margin-bottom: 30rpx;
            .name {
                color: #312C2A;
            }
            .status {
                color: #5780EF;
            }
            .status1 {
                color: #AAAAAA;
            }
        }
        .content-box {
            width: 100%;
            position: relative;
            font-size: 26rpx;
            color: #606672;
            .content-item {
                margin-bottom: 20rpx;
            }
            .icon {
                position: absolute;
                bottom: 0;
                right: 0;
                z-index: 99;
            }
        }
        .btns-box {
            padding-top: 32rpx;
            border-top: 1rpx solid #E8E8E8;
            margin-top: 30rpx;
            @include between(100%);
            .message {
                font-size: 26rpx;
                color: #5780EF;
            }
        }
    }
}

.cancel-pop {
    padding: 40rpx;
    background: #FFFFFF;
    box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153, 153, 153, 0.16);
    border-radius: 30rpx 30rpx 0rpx 0rpx;

    .pop-title {
        color: #000000;
        font-size: 32rpx;
    }

    .info {
        margin-top: 14rpx;
        margin-bottom: 40rpx;
        background: #F6F6F6;
        border-radius: 20rpx;
        padding: 26rpx 30rpx;
        color: #000000;

        &>view {
            margin-bottom: 16rpx;
        }
    }
    .radio-wrap {
        margin-top: 36rpx;
    }
    .btn {
        // box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);
        margin-top: 50rpx;
    }

    .payment-item {
        @include between(100%);
        .left {
            @include start();
            .pay-name {
                color: #000000;
                font-size: 28rpx;
                margin-left: 16rpx;
            }
            .pay-tip {
                margin-left: 16rpx;
                color: #B3BCCC;
            }
        }
    }
    .center {
        margin: 20rpx 0;
    }
}
</style>
